package flirtme.tools;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import flirtme.constants.Constants;
import flirtme.managers.UserManager;
import flirtme.model.ContactModel;
import flirtme.model.CurrentUser;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class ChatConnector {
	Context context;

	public ChatConnector(Context context, ConnectionCreationListener listener) {

		super();
		SmackConfiguration.setPacketReplyTimeout(10000);
		this.context = context;
		XMPPConnection.addConnectionCreationListener(listener);
	}

	public static String getUserNameFromChatEmail(String chatEmail) {
		String[] string = chatEmail.split("[@]");
		return string[0];
	}

	/**
	 * Called by Settings dialog when a connection is establised with the XMPP
	 * server
	 * 
	 * @param connection
	 */
	public void setConnection(XMPPConnection connection) {

		UserManager um = UserManager.instance();
		um.setConnection(connection);
	}

	protected void destroy() {
		try {
			UserManager um = UserManager.instance();
			if (um.getConnection() != null)
				um.getConnection().disconnect();
		} catch (Exception e) {
		}
	}

	public void connect() {

		final ProgressDialog dialog = ProgressDialog.show(this.context,
				"Connecting...", "Please wait...", false);

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				// Create a connection
				ConnectionConfiguration connConfig = new ConnectionConfiguration(
						Constants.HOST, Constants.PORT);
				XMPPConnection connection = new XMPPConnection(connConfig);
				try {
					connection.connect();
				} catch (XMPPException ex) {
					setConnection(null);
				}
				try {
					if (connection.isConnected()) {
						CurrentUser user = UserManager.instance().getUser();

						if (user.getUsername() != null
								&& user.getPassword() != null) {
							connection.login(user.getUsername(),
									user.getPassword());
						}

						Presence presence = new Presence(
								Presence.Type.available);
						connection.sendPacket(presence);
						setConnection(connection);
					}

				} catch (XMPPException ex) {
					setConnection(null);
				}
				dialog.dismiss();
			}
		});
		t.start();
		dialog.show();
	}

}
